<?php

declare(strict_types=1);

namespace App\Middleware;

use App\Service\JwtService;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Contract\ResponseInterface as Response;
use Hyperf\Utils\Context;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Qbhy\SimpleJwt\Exceptions\InvalidTokenException;
use Qbhy\SimpleJwt\Exceptions\SignatureException;
use Qbhy\SimpleJwt\Exceptions\TokenExpiredException;

class AuthMiddleware implements MiddlewareInterface
{


    /**
     * @var Response
     */
    private $response;

    public function __construct(ContainerInterface $container, Response $response)
    {
        $this->response = $response;
    }
    /**
     * @Inject()
     * @var JwtService
     */
    private $JWTService;
    /**
     * 登录验证
     * @param ServerRequestInterface $request
     * @param RequestHandlerInterface $handler
     * @return ResponseInterface
     */
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        try {
            $jwt = $this->JWTService->check($request->getHeader('token')[0] ?? '');
        } catch (InvalidTokenException | SignatureException | TokenExpiredException $e) {
            return $this->response->json(
                \App\Common\Response::fail('token error','004')
            );
        }
        // 将用户信息注入到请求中
        Context::set('user',$this->JWTService->getJwtData($jwt));
        return $handler->handle($request);
    }
}